//
//  GFNearHomeViewController.m
//  GoodFood
//
//  Created by dllo on 15/10/29.
//  Copyright © 2015年 荣伟峰. All rights reserved.
//

#import "GFNearHomeViewController.h"

@interface GFNearHomeViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, GFWaterFlowLayoutDelegate>

@property (nonatomic, strong) UICollectionView *nearCollectionView;
@property (nonatomic, strong) NSMutableArray *rootArray;
@property (nonatomic, assign) NSInteger page;//页数
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, copy) NSString *url;

@end

@implementation GFNearHomeViewController

-(void)creatButton {
    int x = 0;
    NSArray *arr = @[@"附近美食", @"附近餐馆", @"美食杂志"];
    NSArray *arrr = @[@"nearbyfood_btn_icon", @"nearbystore_btn_icon", @"magzine_btn_icon"];
    for (int i = 0; i < 3; i++) {
        
        self.button = [UIButton buttonWithType:UIButtonTypeCustom];
        self.button.frame = CGRectMake(x, 64, ScreenWidth / 3, ScreenWidth / 10);
        self.button.tag = 1000 + i;
        self.button.backgroundColor = [UIColor whiteColor];
        [self.button setTitle:arr[i] forState:UIControlStateNormal];
        [self.button setTitleColor:[UIColor colorWithRed:0.332 green:0.336 blue:0.372 alpha:1.000] forState:UIControlStateNormal];
        [self.button setImage:[UIImage imageNamed:arrr[i]] forState:UIControlStateNormal];
        self.button.titleLabel.font = [UIFont fontWithName:@"OriyaSangamMN" size:15];
        [self.button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.button];
        x += ScreenWidth / 3;
        
    }
    
    
}

-(void)button:(UIButton *)button {
    
    if (button.tag == 1000) {
        
        
        GFNearFoodViewController *nearFoodVC = [[GFNearFoodViewController alloc] init];
        [self.navigationController pushViewController:nearFoodVC animated:YES];
        
    } else if (button.tag == 1001) {
        GFNearResturtantViewController *nearResturantVC = [[GFNearResturtantViewController alloc] init];
        [self.navigationController pushViewController:nearResturantVC animated:YES];
    } else {
        
        GFMagazineViewController *magazineVC = [[GFMagazineViewController alloc] init];
        magazineVC.city_id = self.city_id;
        [self.navigationController pushViewController:magazineVC animated:YES];
        
    }
    
}

-(void)creatNearCollectionView {
    
    GFWaterFlowLayout *layout = [[GFWaterFlowLayout alloc] init];
    layout.delegate = self;
    
    if (self.zineID != 1) {
        self.nearCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64 + ScreenWidth / 10, ScreenWidth, ScreenHeight - 64 - ScreenWidth / 10) collectionViewLayout:layout];
    } else {
        
        self.nearCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64) collectionViewLayout:layout];
    }
    
    
    self.nearCollectionView.backgroundColor = [UIColor whiteColor];
    self.nearCollectionView.dataSource = self;
    self.nearCollectionView.delegate = self;
    [self.view addSubview:self.nearCollectionView];
    
    [self.nearCollectionView registerClass:[GFNearHomeCollectionViewCell class] forCellWithReuseIdentifier:@"near"];
    
    
    self.nearCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh:)];
    self.nearCollectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footRefresh:)];
    
}

#pragma mark - 下拉刷新
- (void)headerRefresh:(MJRefreshHeader *)header {
    [self.view addSubview:self.waitView];
    [self.nearCollectionView.header beginRefreshing];
    self.page = 1;
    [self handleData:self.page];
    [self.nearCollectionView.header endRefreshing];
}
#pragma mark - 上拉加载
- (void)footRefresh:(MJRefreshAutoNormalFooter *)footer {
    [self.view addSubview:self.waitView];
    //    self.resturtantTableView.footer.hidden = NO;
    [self.nearCollectionView.footer beginRefreshing];
    self.page ++;
    [self handleData:self.page];
    [self.nearCollectionView.footer endRefreshing];
}
#pragma mark - 导航
- (void)viewForNavi {
    UIView *view = (UIView *)[self.navigationController.view viewWithTag:10001];
    view.backgroundColor = [UIColor redColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth / 2, ScreenHeight / 3, ScreenWidth / 3, ScreenHeight / 4)];
    label.text = @"最新分享";
    label.textColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.7];
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = label;
    self.view.backgroundColor = [UIColor lightGrayColor];
}

-(void)handleData:(NSInteger)page {
    self.app = [[UIApplication sharedApplication] delegate];
    if (self.city_id == nil) {
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [doc stringByAppendingPathComponent:@"city_id.text"];
        NSError *error = nil;
        NSString *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
        NSInteger ID = [str integerValue];
        self.city_id = @(ID);
    }
        
    if (self.zineID == 1) {
        self.url = [NSString stringWithFormat:@"http://api.meishixing.com/foodzine/weekly/detail/session_id=%@&page=%ld&foodzine_id=%ld",self.app.session_id, self.page, self.foodzine_id];
    } else {
        self.url = [NSString stringWithFormat:@"http://api.meishixing.com/picture/picturelist/last/page=%ld&city_id=%@&session_id=%@", self.page, self.city_id, self.app.session_id];
    }
    NSLog(@"%@",self.url);
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [doc stringByAppendingPathComponent:@"city_id.text"];
    NSError *error = nil;
    [[self.city_id stringValue] writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
    [AFNetHandle GETWithURL:self.url body:nil httpHead:nil responseStyle:JSON success:^(id result) {
       
        NSArray *tempArr = [result objectForKey:@"result"];
        if (self.page == 1) {
            self.rootArray = [NSMutableArray array];
        }
        
        for (NSDictionary *dic in tempArr) {
            GFNearHomeModel *model = [GFNearHomeModel modWithDic:dic];
            [self.rootArray addObject:model];
        }
        [self.nearCollectionView reloadData];
        if (tempArr.count != 0) {
            
            if (self.zineID == 1) {
                if (self.rootArray.count < 10) {
                    self.nearCollectionView.footer.hidden = YES;
                } else {
                    self.nearCollectionView.footer.hidden = NO;
                }
                
            } else
                
                if (self.rootArray.count < 18) {
                    self.nearCollectionView.footer.hidden = YES;
                } else {
                    self.nearCollectionView.footer.hidden = NO;
                }
            
        } else {
            self.nearCollectionView.footer.hidden = YES;
        }
        [self.waitView removeFromSuperview];
        [self.overTimeView removeFromSuperview];
    } fail:^(NSError *error) {
        [self.overTimeView removeFromSuperview];
        self.overTimeView = [[GFOverTimeView alloc] initWithFrame:self.view.frame withButtonBlock:^(UIButton *button) {
            [self.view addSubview:self.waitView];
            [self handleData:self.page];
        }];
        [self.waitView removeFromSuperview];
        [self.view addSubview:self.overTimeView];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self viewForNavi];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self creatNearCollectionView];
    if (self.zineID != 1) {
        [self creatButton];
    }
    self.page = 1;
    [self.view bringSubviewToFront:self.waitView];
    [self handleData:self.page];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"houtui1"] style:UIBarButtonItemStylePlain target:self action:@selector(backToLastVC:)];
    self.navigationItem.leftBarButtonItem = backItem;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sousuo"] style:UIBarButtonItemStylePlain target:self action:@selector(rightButton:)];
    
}

- (void)backToLastVC:(UIBarButtonItem *)item {
    
    if (self.cityID == 1) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    YRSideViewController *con = (YRSideViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    if (self.zineID != 1) {
        [con showLeftViewController:YES];
    }

    
}

-(void)rightButton:(UIBarButtonItem *)rightButton {
    
    GFSearchResturtantViewController *search = [[GFSearchResturtantViewController alloc] init];
    search.city_id = self.city_id;
    
    [self.navigationController pushViewController:search animated:YES];
}


#pragma mark - GFWaterFlowLayoutDelegate

-(CGFloat)waterFlowLayout:(GFWaterFlowLayout *)waterFloeLayout heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath *)indexPath {
    
    GFNearHomeModel *model = self.rootArray[indexPath.item];
    
    
    return ([model.image_height floatValue] / 5) / ((ScreenWidth - 15) / 2) * width + ScreenWidth / 15 + 30 + (ScreenWidth - 15) / 6;
    
}

#pragma mark - UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.rootArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
     GFNearHomeModel *model = [self.rootArray objectAtIndex:indexPath.item];
    void(^block)(void) = ^(void) {
        GFUserInfoViewController *userInfo = [[GFUserInfoViewController alloc] init];
        userInfo.user_id = model.user_id;
        [self.navigationController pushViewController:userInfo animated:YES];
    };
    
    GFNearHomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"near" forIndexPath:indexPath];
    cell.model = model;
    cell.block = block;
    return cell;
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    GFNearHomeDetialViewController *nearHomeDetialVC = [[GFNearHomeDetialViewController alloc] init];
    nearHomeDetialVC.detialArr = [NSMutableArray arrayWithArray:self.rootArray];
    nearHomeDetialVC.city_id = self.city_id;
    nearHomeDetialVC.page = self.page;
    nearHomeDetialVC.num = indexPath.item;
    [self.navigationController pushViewController:nearHomeDetialVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
